<template>
  <q-dialog v-model="importCard">
    <ImportForm mode="parts" @update="init"></ImportForm>
  </q-dialog>
    <q-dialog v-model="searchDig"  >
    <PartsMasterFilterForm ref="partsMasterFilterFormRef" @filter="search"></PartsMasterFilterForm>
  </q-dialog>
  <div class="q-pa-sm report-style">
    <div class="q-gutter-y-md">
      <q-table
        class="card-radius my-table"
        wrap-cells
        flat
        bordered
        :columns="columns"
        :rows="filterRows"
        :pagination="{ rowsPerPage: 15 }"
        row-key="id"
        no-data-label="No parts found."
        no-results-label="The filter didn't uncover any results"
        @row-dblclick="dblclickFn"
      >
        <template v-slot:top>
          <div class="row justify-between" style="width: 100%">
            <div class="fal page-header">Parts Master</div>
            <div>
              <q-card-actions>
                <q-btn
                  class="default-btn"
                  label="Search"
                  no-caps
                  @click="searchDig = true"
                />
                <q-btn
                  class="yellow-btn"
                  icon-right="file_upload"
                  label="Import"
                  no-caps
                  @click="importCard = true"
                />
                <q-btn
                  class="blue-btn"
                  icon-right="archive"
                  label="Export default"
                  no-caps
                  @click="genDefaultCSV()"
                />

                <q-btn
                  label="register"
                  class="default-btn"
                  @click="openRegisterDialog()"
                />
              </q-card-actions>
            </div>
          </div>
        </template>
        <template v-slot:top-row="props">
          <ColsFilter :filter="props.cols" ref="colsFilter"></ColsFilter>
        </template>

        <!-- <template v-slot:body-cell-serial_no="props">
          <q-td :props="props">
              {{ props.value }}
              <ObsolescenceTip v-if="props.row.obsolescence==1"></ObsolescenceTip>
          </q-td>
        </template> -->

        <template v-slot:body-cell-sw_ver="props">
          <q-td
            :props="props"
            :class="
              versionStore.getSwStatusClass(
                props.row.stock_code,
                props.row.sw_ver
              )
            "
          >
            {{ props.value }}
            <q-tooltip class="bg-indigo" :offset="[10, 10]">
              {{ `Latest: ${versionStore.getswVer(props.row.stock_code)} ` }}
            </q-tooltip>
          </q-td>
        </template>

        <template v-slot:body-cell-hw_ver="props">
          <q-td
            :props="props"
            :class="
              versionStore.getHwStatusClass(
                props.row.stock_code,
                props.row.hw_ver
              )
            "
          >
            {{ props.value }}
            <q-tooltip class="bg-indigo" :offset="[10, 10]">
              {{ `Latest: ${versionStore.gethwVer(props.row.stock_code)} ` }}
            </q-tooltip>
          </q-td>
        </template>

        <template v-slot:body-cell-card_installed="props">
          <q-td :props="props">
            {{ props.value }}
          </q-td>
        </template>

        <template v-slot:body-cell-actions="props">
          <q-td>
            <div class="text-left">
              <q-btn
                dense
                round
                flat
                class="edit-btn"
                icon="edit"
                @click.stop="openEditDialog(props.row)"
              ></q-btn>
              <q-btn
                dense
                round
                flat
                class="del-btn"
                @click="deleteFn(props.row.id)"
                icon="delete"
              ></q-btn>
            </div>
          </q-td>
        </template>

        <template v-slot:no-data="{ icon, message }">
          <div class="full-width text-accent q-gutter-sm">
            <!-- <q-icon size="2em" name="sentiment_dissatisfied" /> -->
            <q-icon size="2em" :name="icon" />
            <span> {{ message }} </span>
          </div>
        </template>
      </q-table>
    </div>
  </div>

  <q-dialog full-height v-model="registerDialogVisible">
    <MyBigDialog title="">
      <PartsForm :action="'create'" @update="update"></PartsForm>
    </MyBigDialog>
  </q-dialog>

  <q-dialog full-height v-model="editDialogVisible" @update:model-value="init">
    <MyBigDialog title="">
      <PartsMasterEditComponent
        :editedRow="editedRow"
      ></PartsMasterEditComponent>
    </MyBigDialog>
  </q-dialog>

  <q-dialog v-model="deleteDialogVisible">
    <q-card>
      <q-card-section class="bg-red">
        <div class="text-h6 text-white">
          Are you sure to delete stock code {{}} ?
        </div>
      </q-card-section>

      <q-card-actions align="right">
        <q-btn flat label="Yes" color="primary" v-close-popup />
        <q-btn flat label="No" color="primary" v-close-popup />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { QTableColumn, useQuasar } from 'quasar';
import {ColsFilterType, Parts, partsMashterSearch, stockTtemSearch} from 'src/services/type';
import { computed, ref,getCurrentInstance } from 'vue';
import PartsForm from 'src/components/partsMaster/PartsForm.vue';
import {
  fetchPartWithNumOfChild, fetchPartWithNumOfChildFillter,
  softDeletePart,
} from 'src/services/partsService';
import PartsMasterFilterForm from 'src/components/reportTable/PartsMasterFilterForm.vue';
import { usePartsStore } from 'src/stores/partsStore';
import PartsMasterEditComponent from 'src/components/partsMaster/PartsMasterEditComponent.vue';
import { useVersionStore } from 'src/stores/versionStore';
import MyBigDialog from 'src/components/container/MyBigDialog.vue';
import ColsFilter from 'src/components/table/ColsFilter.vue';
import ObsolescenceTip from 'src/components/ObsolescenceTip.vue';
import { exportTable } from 'src/utils/exportCsvUtils';
import ImportForm from 'src/components/import/importForm.vue';
import {getStockItemWithChildNumberFilter} from "@/services/stockCodeService";

const $q = useQuasar();

const useParts = usePartsStore();
const versionStore = useVersionStore();
const editedRow = ref();
const editDialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const registerDialogVisible = ref(false);

const colsFilter = ref<typeof ColsFilter>();

const searchDig = ref(false)
const importCard = ref(false);

function openRegisterDialog() {
  registerDialogVisible.value = true;
}

function openEditDialog(row: Parts) {
  editedRow.value = { ...row };
  editDialogVisible.value = true;
}

function openDeleteDialog(row: Parts) {
  console.log('delte', row);

  deleteDialogVisible.value = true;
}

function closeDialog() {
  editDialogVisible.value = false;
  registerDialogVisible.value = false;
  init();
}

function dblclickFn(evt: any, row: Parts, index: number) {
  editedRow.value = { ...row };
  editDialogVisible.value = true;
}

const align = 'left';

const columns = [
  /*  {
    name: 'id',
    label: '#',
    field: 'id',
    sortable: true,
    search: false,
    align,
  }, */
  {
    name: 'stock_code',
    label: 'Stock Code',
    field: 'stock_code',
    sortable: true,
    classes: 'my-td',
    align,
  },
  {
    name: 'serial_no',
    label: 'Serial No',
    field: 'serial_no',
    sortable: true,
    align,
  },

  {
    name: 'short_description',
    label: 'Short Description',
    field: 'description',
    sortable: true,
    align,
  },
  {
    name: 'car',
    label: 'Location',
    field: 'car',
    sortable: true,
    align,
  },
  {
    name: 'sw_ver',
    label: 'S/W Version',
    field: 'sw_ver',
    sortable: true,
    align,
  },
  {
    name: 'hw_ver',
    label: 'H/W Version',
    field: 'hw_ver',
    sortable: true,
    align,
  },
  /*   {
    name: 'asset_id',
    label: 'Asset ID from EAMS',
    field: 'asset_id',
    sortable: true,
    align,
  }, */
  {
    name: 'card_installed',
    label: 'No Of Childs',
    field: 'card_installed',
    sortable: true,
    align,
  },
  {
    name: 'parent_short_description',
    label: 'Parent Short Description',
    field: 'parent_short_description',
    sortable: true,
    format:(val: string, row: Parts) => {
      if(val==''){
        return '-'
      }
      return val
    },
    align,
  },
  {
    name: 'parent_serial_no',
    label: 'Parent Serial No',
    field: 'parent_serial_no',
    sortable: true,
    format:(val: string, row: Parts) => {
      if(val==''){
        return '-'
      }
      return val
    },
    align,
  },
  {
    name: 'actions',
    label: 'Actions',
    field: 'actions',
    search: false,
    align,
  },
];

const rows = ref<Parts[]>([]);

const partsMasterFilterFormRef = ref(null)

async function init() {
  // versionStore.init();
  // const data = await fetchPartWithNumOfChild();
  // rows.value = data.data;
  importCard.value = false;
}
init();

async function update() {
  registerDialogVisible.value = false;
  await init();
  if (rows.value) {
    console.log(rows.value[0]);
    editedRow.value = { ...rows.value[0] };
    editDialogVisible.value = true;
  }
}

function deleteFn(id: number) {
  $q.dialog({
    title: 'Confirm',
    message: 'Are you sure to delete this record?',
    cancel: true,
  }).onOk(async () => {
    const res = await softDeletePart(id);
    if (res) {
      $q.notify({
        message: 'Success',
        color: 'positive',
      });
      init();
    }
  });
}

async function genDefaultCSV() {
  const row = rows.value[0];
  console.log(row);
  const cols = [];
  for (const col in row) {
    if (
      col == 'serial_no' ||
      col == 'stock_code' ||
      col == 'obsolescence' ||
      col == 'date_code' ||
      // col=='location'||
      // col=='system'||
      // col=='workgroup'||
      col == 'sw_ver' ||
      col == 'hw_ver'||
      col == 'sequence'||
      col == 'description'||
      col == 'parent_stock_code'||
      col == 'parent_serial_no'
    ) {
      cols.push({
        name: col,
        label: col,
        field: col,
        sortable: true,
  
        align,
      });
    }
  }
 

  const output = filterRows.value.sort(compareNumbers).map((item) => {
    if (item.obsolescence == 1) {
      return {
        ...item,
        obsolescence: 'YES',
      };
    }
    if (item.obsolescence == 0) {
      return {
        ...item,
        obsolescence: 'NO',
      };
    }
  });
  exportTable(cols, output, 'Parts Master');
}
function compareNumbers(a: Parts, b: Parts) {
  return a.id - b.id;
}

function filterFn(row: Parts) {
  if (colsFilter.value) {
    return colsFilter.value.filterFn(row);
  }
}

const filterRows = computed(() => {
  console.log(rows.value);

  return rows.value?.filter(filterFn);
});

function showLoading() {
  $q.loading.show({
    message: 'Doing something. Please wait...',
    boxClass: 'bg-grey-2 text-grey-9',
    spinnerColor: 'primary',
  });
}
async function search(form: { data: partsMashterSearch}){
  partsMasterFilterFormRef.value.myDialogSubmitLonding(true);
  // showLoading()
  const res =  await fetchPartWithNumOfChildFillter(form.data.stock_code, form.data.serial_no, form.data.description)
  console.log(res);
    if (res.data) {
    rows.value = res.data;
    console.log(res.data);
  }
  searchDig.value = false
  // $q.loading.hide()
  partsMasterFilterFormRef.value.myDialogSubmitLonding(false);
}
</script>

<style scoped>
.content {
  display: flex;
  justify-content: space-between;
  background-color: #eef4fa;
  padding-top: 20px;
  padding-left: 20px;
  padding-right: 10px;
}

.warning {
  color: red;
  font-weight: bold;
  text-align: center;
  width: -webkit-fill-available;
  padding-top: 20px;
}

th,
td {
  text-align: left;
  padding: 10px;
}

.row-bg {
  background-color: #d9d9d9;
}

.row-bg-light {
  background-color: #eeeded;
}

.match {
  background-color: #b3ffd7;
}

.not-match {
  background-color: #ebc0c0;
}
</style>
